﻿using SGA.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

namespace SGA.Authentication.Admin
{
    public partial class Role : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Method to verify if the inserting data is valid
        /// and to create membership role (System.Web.Security)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LVAccessRoles_ItemInserting(object sender, ListViewInsertEventArgs e)
        {
            try
            {
                string role = e.Values["Role"].ToString();
                if (Roles.RoleExists(role))
                {
                    throw new Exception("Nível de acesso já existe. Não é permitido duplicações.");
                }

                Roles.CreateRole(role);
                NotificationLabel.Text = String.Format("O nível de acesso: {0} foi criado com sucesso.", role);
                NotificationLabel.CssClass = "mySuccess";
            }

            catch (Exception ex)
            {
                e.Cancel = true;
                NotificationLabel.Text = String.Format("{0}", ex.Message);
                NotificationLabel.CssClass = "Alert";
            }
        }

        /// <summary>
        /// Method to verify if the inserting data is valid
        /// and to delete membership role (System.Web.Security)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void LVAccessRoles_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
            int idRole = (int)e.Keys[0];
            AccessRoles accessRole;
            using (var bd = new MailingEntities())
            {
                var query = (from role in bd.AccessRoles
                             where role.Id == idRole
                             select role).SingleOrDefault();
                accessRole = query;
            }
                NotificationLabel.Text = String.Format("O nível de acesso: {0} foi removido com sucesso.", accessRole.Role);
                NotificationLabel.CssClass = "mySuccess";
        }
        /// <summary>
        /// Method to remove users at role and then delete the role
        /// </summary>
        /// <param name="role"></param>
        private void deleteRole(string role)
        {
            string[] users = Roles.GetUsersInRole(role);
            if (users.Length > 0)
            {
                Roles.RemoveUsersFromRole(users, role);
            }
            Roles.DeleteRole(role);
        }
    }
}